export const MEANINGFUL_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'pre', 'div'];

export const TOOLBAR_HEIGHT = 48; // 工具栏高度
export const STATUS_BAR_HEIGHT = 48; // 状态栏高度（固定为48）
export const BORDER_HEIGHT = 2; // 边框高度
export const CONTENT_MIN_HEIGHT = 30; // 内容最小高度
export const CONTAINER_MIN_HEIGHT = TOOLBAR_HEIGHT + STATUS_BAR_HEIGHT + BORDER_HEIGHT + CONTENT_MIN_HEIGHT; // 128

declare global {
  interface Window {
    tinymce?: any;
  }
}

export function computeWordCount(text) {
  try {
    const chineseChars = (text.match(/[\u4e00-\u9fa5]/g) || []).length;
    const englishWords = (text.match(/[a-zA-Z]+/g) || []).length;
    // 新增：统计数字序列（如“123”算1个token）
    const numberTokens = (text.match(/\d+/g) || []).length;
    return chineseChars + englishWords + numberTokens;
  } catch (e) {
    return 0;
  }
}

export function resolveTagFromNode(node) {
  if (!node) return 'P';
  const tagName = (node.nodeName || '').toLowerCase();
  if (MEANINGFUL_TAGS.includes(tagName)) return tagName.toUpperCase();
  const parent = node.parentNode;
  if (parent) {
    const parentTag = (parent.nodeName || '').toLowerCase();
    if (MEANINGFUL_TAGS.includes(parentTag)) return parent.nodeName.toUpperCase();
  }
  return 'P';
}

export function scrollToCursor(editor) {
  if (!editor) return;
  try {
    const selection = editor.selection;
    if (!selection) return;
    const range = selection.getRng();
    if (!range) return;

    let element = range.startContainer;
    if (element && element.nodeType === Node.TEXT_NODE) {
      element = element.parentElement;
    }
    if (!element) return;

    // 修复：通过编辑器实例获取正确的容器，而不是使用document.querySelector
    const editorElement = editor.getElement();
    if (!editorElement) return;
    
    // 从编辑器元素向上查找包含.editable-content类的容器
    const editorContainer = editorElement.closest('.editable-content') || editorElement;
    if (!editorContainer) return;

    const elementRect = element.getBoundingClientRect();
    const containerRect = editorContainer.getBoundingClientRect();

    const relativeTop = elementRect.top - containerRect.top;
    const relativeBottom = elementRect.bottom - containerRect.top;

    const containerPadding = 24; // 对应.editable-content的padding-top
    const scrollableHeight = editorContainer.clientHeight - (containerPadding * 2);

    const threshold = 50; // 提前50px开始滚动
    if (relativeBottom > scrollableHeight - threshold) {
      const scrollAmount = relativeBottom - scrollableHeight + threshold;
      (editorContainer as HTMLElement).scrollTop += scrollAmount;
    } else if (relativeTop < containerPadding + threshold) {
      const scrollAmount = relativeTop - containerPadding - threshold;
      (editorContainer as HTMLElement).scrollTop += scrollAmount;
    }
  } catch (error) {
    console.warn('自动滚动到光标位置时出错:', error);
  }
}

export function loadTinyMCEScript() {
  return new Promise((resolve, reject) => {
    if (window.tinymce) {
      resolve(window.tinymce);
      return;
    }
    const script = document.createElement('script');
    script.src = '/tinymce/js/tinymce/tinymce.min.js';
    script.onload = () => resolve(window.tinymce);
    script.onerror = () => reject(new Error('Failed to load TinyMCE'));
    document.head.appendChild(script);
  });
} 